from django.views import View
from django.http import JsonResponse, QueryDict
from . import script_manage, forms
import json
from django.core.files.base import ContentFile
from rest_framework.views import APIView
from rest_framework.request import Request
from common.response import Reponse


class ScriptsView(View):

    # 上传脚本
    def post(self, request):
        payload = Reponse()
        script_info = {
            "name": request.POST.get('name'),
            "script_type": request.POST.get('type'),
            "desc": request.POST.get('desc'),
            "time_out": request.POST.get('time_out'),
            "tenant_id": request.environ.get('HTTP_TENANT_ID'),
            "content": request.POST.get('content'),
            "content_file": request.FILES.get('content_file')
        }
        # playbook时，清除脚本内容
        if "Playbook" == script_info.get('script_type'):
            script_info['content'] = ""
        # 判断脚本文件是否存在，如果存在脚本内容，将脚本内容转换为文件
        if script_info.get('content'):
            script_info['content_file'] = ContentFile(
                script_info.get('content'), script_info.get('name'))
        elif not script_info.get('content_file'):
            payload.status = "error"
            payload.errmsg = r"Script conetnt or content_file not exist."

        # 验证表单
        f = forms.ScriptForm(script_info)
        if not f.is_valid():
            payload.status = "error"
            payload.errmsg = str(f.errors)
            return payload.json_response()
        else:
            try:
                payload.data = script_manage.post_script(script_info)
            except Exception as e:
                payload.status = "error"
                payload.errmsg = str(e)
                return payload.json_response()
            payload.status = "ok"
            payload.msg = "Scipt upload success."
            return payload.json_response()

        return payload.json_response()

    # 获取脚本

    def get(self, request):
        payload = Reponse()
        param = {
            "pageNumber": request.GET.get('pageNumber'),
            'pageSize': request.GET.get('pageSize'),
            'name': request.GET.get('name'),
            'script_type': request.GET.get('type')
        }
        f = forms.ScriptListForm(param)
        if not f.is_valid():
            payload.status = "error"
            payload.errmsg = str(f.errors)
            return JsonResponse(payload)
        else:
            try:
                payload.data = script_manage.get_scripts(param)
            except Exception as e:
                payload.status = "error"
                payload.errmsg = str(e)
                return payload.json_response()
            payload.status = "ok"
            payload.msg = "Get script list success."
            return payload.json_response()
        return payload.json_response()

    def delete(self, request):
        payload = {}
        return JsonResponse(payload)

    def put(self, request):
        payload = {}
        return JsonResponse(payload)


class ScriptView(APIView):
    # 获取脚本详情
    def get(self, request, **kwargs):
        payload = Reponse()
        script_id = kwargs.get('script_id')
        try:
            script = script_manage.get_script(script_id)
            history = script_manage.get_history(script_id)
            payload.data.update(script)
            payload.data.update({"history": history})
            payload.status = 'ok'
            payload.msg = "Get script success."
        except Exception as e:
            payload.status = "error"
            payload.errmsg = str(e)
            return payload.json_response()
        return payload.json_response()

    def post(self, request):
        payload = {}
        return JsonResponse(payload)

    # 删除脚本
    def delete(self, request, **args):
        payload = Reponse()
        script_id = args.get('script_id')
        try:
            payload.data = script_manage.delete_script(script_id)
            payload.status = 'ok'
            payload.msg = "Delete script success."
        except Exception as e:
            payload.status = 'error'
            payload.errmsg = str(e)
        return payload.json_response()

    # 更新脚本

    def put(self, request: Request, **kwargs):
        payload = Reponse()
        script_id = kwargs.get('script_id')
        try:
            payload.data = script_manage.update_script(
                script_id,
                name=request.data.__getitem__('name'),
                desc=request.data.__getitem__('desc'),
                time_out=request.data.__getitem__('time_out'),
                content=request.data.__getitem__('content'),
                content_file=request.data.__getitem__('content_file'))
            payload.status = 'ok'
            payload.msg = "Update script success."
        except Exception as e:
            payload.status = 'error'
            payload.errmsg = str(e)
        return payload.json_response()
